package com.itheima.order.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.goods.pojo.Address;
import com.itheima.goods.pojo.Goods;
import com.itheima.goods.pojo.Order;
import com.itheima.order.feign.GoodsFeign;
import com.itheima.order.feign.UserFeign;
import com.itheima.order.mapper.OrderDao;
import com.itheima.order.service.OrderService;
import entity.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author wang
 * @description
 * @date 2021/7/31 15:33
 */
@Service("orderService")
@Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
public class OrderServiceImpl extends ServiceImpl<OrderDao, Order> implements OrderService {
    @Autowired
    UserFeign userFeign;
    @Autowired
    GoodsFeign goodsFeign;

    @Override
    public Result getSubmitInfo(Integer goodId) {
        Map map = new HashMap();
        // 获取当前登录用户，未登录提示登录
        // 根据登录用户 查询用户微服务中的 地址列表信息
        List<Address> addressList = userFeign.findByUserId("zhubajie");
        // 根据商品ID  查询商品信息(价格 图片 标题)
        Result<Goods> goodsResult = goodsFeign.findById(goodId);
        System.out.println(11);
        Goods goods = goodsResult.getData(); //  获得商品数据
        // 封装 返回
        map.put("addressList", addressList);
        map.put("goods", goods);
        return new Result(true, "查询成功", map);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED,readOnly = false)
    public Result submitOrder(Order order) {
        // 创建订单
        if (order == null || order.getGoodId() == null) {
            return new Result(false, "订单信息错误");
        }
        //调用goods服务购买方法
        Result buyResult = goodsFeign.buy(order.getGoodId(), 1);
        //如果未购买成功
        if (!buyResult.isFlag()) {
            return buyResult;
        }
        //如果购买成功，添加订单信息
        order.setStatus("1");
        order.setCreateTime(new Date());
        order.setUpdateTime(new Date());
        order.setUserId("zhubajie");
        this.save(order);
        return new Result(true,"创建订单成功",String.valueOf(order.getOrderId()));
    }
}
